package com.base

import com.orhanobut.logger.Logger
import okhttp3.Interceptor
import okhttp3.Response
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException

class HttpInterceptor(): Interceptor {
    private var result: String? = null

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val httpCode: Int = response.code() //获取响应码
        val url = request.url().toString()
        val responseBody = response.body()
        val source = responseBody?.source()
        val buffer = source?.buffer()
        val utf8 = Charset.forName("UTF-8")
        source?.request(Long.MAX_VALUE) // Buffer the entire body.
        var charset: Charset = utf8
        val contentType = responseBody?.contentType()
        if (contentType != null) {
            try {
                charset = contentType.charset(utf8)!!
            } catch (e: UnsupportedCharsetException) {
                //无法解码响应体;字符集可能是畸形的。
                return response
            }
        }
        result = buffer?.clone()?.readString(charset)
        Logger.d("httpCode: $httpCode")
        Logger.d("url: $url")
        Logger.d("Data: $result");

        return response

    }
}